// src/viewpage/follow.tsx
import { message } from 'antd';

export class FollowService {
  static async fetchFollowCounts(userId: string, token: string): Promise<{ followCount: number; followerCount: number }> {
    try {
      let followCount = 0;
      let followerCount = 0;

      console.log('开始获取关注数量，用户ID:', userId);

      // 获取关注数量（我关注的人数）
      try {
        const followingResponse = await fetch(`/api/userfollows/follower/${userId}/count`, {
          method: 'GET',
          headers: { 
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
        });
        
        if (followingResponse.ok) {
          const followingData = await followingResponse.json();
          followCount = typeof followingData === 'number' ? followingData : followingData.count || 0;
          console.log('关注数量接口成功:', followCount);
        } else {
          console.log('关注数量接口失败，状态:', followingResponse.status);
        }
      } catch (apiError) {
        console.error('关注数量接口异常:', apiError);
      }

      // 获取粉丝数量（关注我的人数）
      try {
        const followersResponse = await fetch(`/api/userfollows/followee/${userId}/count`, {
          method: 'GET',
          headers: { 
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
        });
        
        if (followersResponse.ok) {
          const followersData = await followersResponse.json();
          followerCount = typeof followersData === 'number' ? followersData : followersData.count || 0;
          console.log('粉丝数量接口成功:', followerCount);
        } else {
          console.log('粉丝数量接口失败，状态:', followersResponse.status);
        }
      } catch (apiError) {
        console.error('粉丝数量接口异常:', apiError);
      }

      // 备用方案：如果专用接口失败，使用通用接口手动计算
      if (followCount === 0 || followerCount === 0) {
        console.log('使用备用方案获取关注数据');
        try {
          const response = await fetch(`/api/userfollows`, {
            method: 'GET',
            headers: { 
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'application/json'
            },
          });

          if (response.ok) {
            const allFollows = await response.json();
            const userIdNum = parseInt(userId);
            
            console.log('获取到所有关注关系:', allFollows);
            
            // 关注数量：followerId = 当前用户ID的记录数 (我关注的人)
            if (followCount === 0) {
              followCount = allFollows.filter((follow: any) => 
                follow.followerId === userIdNum
              ).length;
            }
            
            // 粉丝数量：followeeId = 当前用户ID的记录数 (关注我的人)
            if (followerCount === 0) {
              followerCount = allFollows.filter((follow: any) => 
                follow.followeeId === userIdNum
              ).length;
            }
            
            console.log('备用方案计算结果 - 关注:', followCount, '粉丝:', followerCount);
          }
        } catch (fallbackError) {
          console.error('备用方案也失败:', fallbackError);
        }
      }

      return { followCount, followerCount };
    } catch (error) {
      console.error('获取关注数量完全失败:', error);
      return { followCount: 0, followerCount: 0 };
    }
  }

  static async checkIfFollowing(targetUserId: number, token: string): Promise<boolean> {
    try {
      const currentUserId = localStorage.getItem('userId');
      if (!currentUserId) {
        console.log('未找到当前用户ID');
        return false;
      }

      console.log('检查关注状态，当前用户:', currentUserId, '目标用户:', targetUserId);

      // 方法1: 使用获取关注列表的方式检查
      try {
        const response = await fetch(`/api/userfollows/follower/${currentUserId}/followees`, {
          method: 'GET',
          headers: { 
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
        });

        if (response.ok) {
          const followees = await response.json();
          console.log('获取到的关注列表:', followees);
          
          // 检查目标用户是否在关注列表中
          const isFollowing = followees.some((follow: any) => 
            follow.followeeId === targetUserId
          );
          console.log('关注状态检查结果:', isFollowing);
          return isFollowing;
        } else {
          console.log('获取关注列表失败，状态:', response.status);
        }
      } catch (checkError) {
        console.error('关注列表检查异常:', checkError);
      }

      // 方法2: 备用方案 - 获取所有关注关系检查
      console.log('使用备用方案检查关注状态');
      const allFollowsResponse = await fetch(`/api/userfollows`, {
        method: 'GET',
        headers: { 
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
      });

      if (allFollowsResponse.ok) {
        const allFollows = await allFollowsResponse.json();
        const isFollowing = allFollows.some((follow: any) => 
          follow.followerId === parseInt(currentUserId) && 
          follow.followeeId === targetUserId
        );
        console.log('备用方案检查结果:', isFollowing);
        return isFollowing;
      }
    } catch (error) {
      console.error('检查关注状态失败:', error);
    }
    return false;
  }

  static async handleFollow(
    userProfile: any, 
    isFollowing: boolean, 
    setIsFollowing: (value: boolean) => void,
    setFollowerCount: (updater: (prev: number) => number) => void
  ): Promise<void> {
    if (!userProfile) return;

    try {
      const token = localStorage.getItem('token') || sessionStorage.getItem('token');
      const currentUserId = localStorage.getItem('userId');

      if (!token || !currentUserId) {
        message.warning('请先登录');
        return;
      }

      console.log('执行关注操作，当前状态:', isFollowing, '目标用户:', userProfile.id);

      if (isFollowing) {
        // 取消关注 - 使用正确的API格式
        const response = await fetch(`/api/userfollows/${currentUserId}/${userProfile.id}`, {
          method: 'DELETE',
          headers: { 
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
        });

        if (response.ok) {
          setIsFollowing(false);
          message.success('已取消关注');
          setFollowerCount(prev => Math.max(0, prev - 1));
          console.log('取消关注成功');
        } else {
          const errorText = await response.text();
          message.error(`取消关注失败: ${response.status}`);
          console.error('取消关注失败，状态:', response.status, '错误信息:', errorText);
        }
      } else {
        // 关注 - 确保请求体格式正确
        const followData = {
          followerId: parseInt(currentUserId),
          followeeId: userProfile.id
        };
        
        console.log('发送关注请求:', followData);
        
        const response = await fetch(`/api/userfollows`, {
          method: 'POST',
          headers: { 
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(followData),
        });

        if (response.ok) {
          setIsFollowing(true);
          message.success('关注成功');
          setFollowerCount(prev => prev + 1);
          console.log('关注成功');
        } else {
          const errorText = await response.text();
          message.error(`关注失败: ${response.status}`);
          console.error('关注失败，状态:', response.status, '错误信息:', errorText);
        }
      }
    } catch (error) {
      message.error('操作失败，请检查网络连接');
      console.error('关注操作异常:', error);
    }
  }
}